package com.wwcom.darteagle;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.wwcom.darteagle.data.DartEagleDatabase;
import com.wwcom.darteagle.model.GlobalAppData;
import com.wwcom.darteagle.model.Match;
import com.wwcom.darteagle.model.MatchPlayer;
import com.wwcom.darteagle.model.Score;
import com.wwcom.darteagle.util.Messages;
import com.wwcom.darteagle.util.Settings;
import com.wwcom.darteagle.view.ScoreEntryView;
import com.wwcom.darteagle.view.ScoreMatrixPlayerView;

public class ScoreEntryActivity extends Activity {
	private int visitInd;
	private int playerInd;
	private MatchPlayer editPlayer;	
	private Match match;
	private Score editScore;
	private ScoreEntryView scoreEntryView;
	
	private static final String RELOAD_MATCH= "reloadMatch";
	private static final String DART1_SCORE= "dart1Score";
	private static final String DART2_SCORE= "dart2Score";
	private static final String DART3_SCORE= "dart3Score";
	private static final String DART1_DOUBLE= "dart1Double";
	private static final String DART2_DOUBLE= "dart2Double";
	private static final String DART3_DOUBLE= "dart3Double";
	private static final String DART1_TREBLE= "dart1Treble";
	private static final String DART2_TREBLE= "dart2Treble";
	private static final String DART3_TREBLE= "dart3Treble";
	public static final String VISIT_IND= "visitInd";
	public static final String PLAYER_IND= "playerInd";
	
	LocalBroadcastManager mLocalBroadcastManager;
    BroadcastReceiver mReceiver;

	/** Called when the activity is first created. */	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setTheme(Settings.getThemeID(this));    	

        Log.d("ScoreEntry","onCreate");
        
        GlobalAppData gd= GlobalAppData.getSingletonInstance();
		 
        //recover saved state
        visitInd= -1;
        playerInd= -1;
		if (savedInstanceState != null) {
			if (savedInstanceState.getBoolean(RELOAD_MATCH) && gd.match == null) {
				DartEagleDatabase db= new DartEagleDatabase(this);             	    	
				gd.match= db.getResumableMatch();
				db.close();
			}
			visitInd= savedInstanceState.getInt(VISIT_IND);
			playerInd= savedInstanceState.getInt(PLAYER_IND);
		}   
        Bundle extras = getIntent().getExtras();
        if(extras !=null)
        {
        	visitInd= extras.getInt(VISIT_IND);
        	playerInd= extras.getInt(PLAYER_IND);
        }
        
		match= gd.match;
        
        setContentView(R.layout.score_entry);
		scoreEntryView= (ScoreEntryView)findViewById(R.id.score_entry_view);    				
                       
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
	    IntentFilter filter = new IntentFilter();
	    filter.addAction(Messages.MATCH_UPDATE_FINALISED);
	    filter.addAction(Messages.MATCH_UPDATE);
	    final Activity activity= this;
	    mReceiver= new BroadcastReceiver() {
			 @Override
			 public void onReceive(Context arg0, Intent arg1) {
				if (arg1.getAction().equals(Messages.MATCH_UPDATE_FINALISED)) {
			        activity.finish();					 
				} else if (arg1.getAction().equals(Messages.MATCH_UPDATE)) {
			        ((ScoreMatrixPlayerView)findViewById(R.id.score_matrix_player_view)).updateView();					 
				}
			 }
			 
		 }; 
		 mLocalBroadcastManager.registerReceiver(mReceiver, filter);	
		 scoreEntryView.setBroadcastManager(mLocalBroadcastManager);		 

        //check whether we are editing an already entered score
        editPlayer= null;
        editScore= null;
        if(playerInd >= 0 && visitInd >= 0)
        {
        	editPlayer= match.getMatchPlayers().get(playerInd);
        	scoreEntryView.setLegHistoryPosition(visitInd, editPlayer);
			editScore= new Score(match.getVisitScore(editPlayer, visitInd).getUnvalidatedScore());
			match.unFinalisePlayerScore(editPlayer, visitInd);
        }
        
        //check if we are dealing with a configuration change
		if (savedInstanceState != null) {
			int dartScore1= savedInstanceState.getInt(DART1_SCORE);
			int dartScore2= savedInstanceState.getInt(DART2_SCORE);
			int dartScore3= savedInstanceState.getInt(DART3_SCORE);
			boolean isDouble1= savedInstanceState.getBoolean(DART1_DOUBLE);
			boolean isDouble2= savedInstanceState.getBoolean(DART2_DOUBLE);
			boolean isDouble3= savedInstanceState.getBoolean(DART3_DOUBLE);
			boolean isTreble1= savedInstanceState.getBoolean(DART1_TREBLE);
			boolean isTreble2= savedInstanceState.getBoolean(DART2_TREBLE);
			boolean isTreble3= savedInstanceState.getBoolean(DART3_TREBLE);
        	scoreEntryView.resetFields(visitInd, editPlayer,
        			isDouble1, isDouble2, isDouble3,
        			isTreble1, isTreble2, isTreble3,
        			dartScore1, dartScore2, dartScore3);
        }

    }
        
    @Override 
    protected void onSaveInstanceState (Bundle outState) {
    	super.onSaveInstanceState(outState);
    	//note that we have been killed and will need to reload the gd.match from
    	// the database
    	outState.putBoolean(RELOAD_MATCH, true);
    	outState.putInt(DART1_SCORE,scoreEntryView.getDartScoreUnmodified(R.id.dartScore1));
    	outState.putInt(DART2_SCORE,scoreEntryView.getDartScoreUnmodified(R.id.dartScore2));
    	outState.putInt(DART3_SCORE,scoreEntryView.getDartScoreUnmodified(R.id.dartScore3));
    	outState.putBoolean(DART1_DOUBLE,scoreEntryView.getIsDouble(R.id.dartScore1));
    	outState.putBoolean(DART2_DOUBLE,scoreEntryView.getIsDouble(R.id.dartScore2));
    	outState.putBoolean(DART3_DOUBLE,scoreEntryView.getIsDouble(R.id.dartScore3));
    	outState.putBoolean(DART1_TREBLE,scoreEntryView.getIsTreble(R.id.dartScore1));
    	outState.putBoolean(DART2_TREBLE,scoreEntryView.getIsTreble(R.id.dartScore2));
    	outState.putBoolean(DART3_TREBLE,scoreEntryView.getIsTreble(R.id.dartScore3));
    	outState.putInt(VISIT_IND,visitInd);
    	outState.putInt(PLAYER_IND,playerInd);
    }
    
    @Override
    public void onBackPressed() {
    	if (editPlayer != null) {
    		//revert to what the score was previsouly
    		match.updatePlayerScore(editPlayer,visitInd,editScore);
    		match.finalisePlayerScore(editPlayer, visitInd);
    	}
    	super.onBackPressed();

    }
    
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mLocalBroadcastManager.unregisterReceiver(mReceiver);
		Log.d("ScoreEntry","onDestroy");
	}        
      
}